
let conf = {
    iceServers: [
        {
            urls: `stun:stun.l.google.com:19302`,
            username: '',
            credential: ''
        }
    ],
    iceTransportPolicy: 'all',
    bundlePolicy: 'max-bundle',
    rtcpMuxPolicy: 'require',
    sdpSemantics: 'unified-plan'
};


let peerConnection = new RTCPeerConnection(conf);

let remoteStream;

let init= async () => {
    remoteStream = new MediaStream()
    document.getElementById('user-2').srcObject = remoteStream

    peerConnection.ontrack = (event) =>{
        event.streams[0].getTracks().forEach((track) =>{
             remoteStream.addTrack(track);
        });
    }

    document.getElementById('create-answer').addEventListener('click',createAnswer)
    document.getElementById('add-ice').addEventListener('click',addICE)
}

let createAnswer = async() =>{
    peerConnection.onicecandidate = async (event) =>{
        if(event.candidate)
        {
            console.log('on ice')
            document.getElementById('answer-sdp').value = JSON.stringify(peerConnection.localDescription);
            document.getElementById('gen-ice').value = JSON.stringify(event.candidate);

        }
    }

    let offer = JSON.parse(document.getElementById('offer-sdp').value)
    await peerConnection.setRemoteDescription(offer)


    let answer = await peerConnection.createAnswer();
    await peerConnection.setLocalDescription(answer);
    console.log('set remoete sdp sucess');

    document.getElementById('answer-sdp').value = JSON.stringify(peerConnection.localDescription);
}

let addICE = async()=>{
    let ice = JSON.parse(document.getElementById('ice').value)
    peerConnection.addIceCandidate(ice);
    console.log("add ICE candidate:"+ice);
}

init()

